# -*- coding: utf-8 -*-
# @Time    : 2018/2/13 0:13
# @Author  : Soft
# @File    : view.py
# @Desc    : 作业管理的视图控制器、
import os
import logging
from werkzeug.utils import secure_filename
from module.AuthUtil import auth_required
from module.ExeclUtils.RecordExcel import getRecordExecl
from module.ExeclUtils.WorkExecl import getWorkExecl
from module.TimeUtils import *
from module.cache import cache
from module.user.service import StuService
from module.work import work
from module.work.service import WorkService
from module.user import u_login
from module.class_.service import ClzService
from module.admin import ad_login
from flask import jsonify, request, current_app, send_from_directory, send_file
from config import WorkUp, WORK_FOLDER

cache.set('work_lock', True)
log = logging.getLogger("work controller")


@work.route('/lock/<can>', methods=['post'])
@ad_login.required
def lock(can):
    if can == 'open':
        cache.set('work_lock', False)
    else:
        cache.set('work_lock', True)
    return jsonify(status=True, lock=cache.get('work_lock'))


# 有问题 循环请求 很大的问题 导致阻塞
@work.route('/download/<kid>/<sid>/<filename>')
@ad_login.required
def download(kid, sid, filename):
    version = int(request.args.get('version', '0'))
    has_k = WorkService.is_has(sid=sid, kid=kid)
    if has_k[0]:
        if version == has_k[1].get('version'):
            try:
                stu_name = StuService.find_by_id(sid).stu_name
                k_name = ClzService.getById(kid).k_name
                directory = os.path.join(current_app.root_path, WORK_FOLDER + kid + '/' + sid)
                return send_from_directory(directory, filename, as_attachment=True,
                                           attachment_filename=k_name + "_" + stu_name + ".zip")
            except BaseException as be:
                log.debug('download filed --> %s' % be)
                return jsonify(status=False, msg=be)
        return jsonify(status=False, code=401, msg='Homework version is not correct, The refresh retry')
    return jsonify(status=False, code=401, msg='Record does not exist')


@work.route('/upload', methods=['post'])
@auth_required
def upload():
    """
    上传作业 文件name为work 提交k_id 不支持中文名
    """
    kid = request.form.get('k_id')
    sid = request.form.get('stu_id')
    is_k = ClzService.is_has(kid=kid)
    if kid and is_k[0]:  # 当课程存在的时候才能上传作业
        limit = work_limit(is_k[1].get('k_time'), is_k[1].get('k_work_endtime'))
        if isinstance(limit, int):
            if limit == WorkUp.YJ or not cache.get('work_lock'):
                wf = request.files['work']
                filename = secure_filename(wf.filename)
                try:
                    tp = filename[filename.rindex('.') + 1:]
                    if tp == 'zip':
                        folder = str(kid) + '/' + str(sid) + '/'
                        real_folder = os.path.join(current_app.root_path, WORK_FOLDER + folder)
                        if os.path.exists(real_folder):
                            for f in os.listdir(real_folder):  # 清除已经提交过的作业 重新上传
                                file_path = os.path.join(real_folder, f)
                                if os.path.isfile(file_path):
                                    os.remove(file_path)
                        else:
                            os.makedirs(real_folder)
                        # print real_folder
                        wf.save(real_folder + filename)
                        return jsonify(status=True, work_url=request.host_url + 'work/download/' + folder + filename,
                                       filename=filename)
                except BaseException as e:
                    log.error("文件保存错误--> %s" % e)
                    return jsonify(status=False, msg='文件保存异常，请改为英文名')
                return jsonify(status=False, msg='只支持zip格式文件')
            return jsonify(status=False, msg='作业不允许逾期提交')
        return jsonify(status=False, msg='课程还未开始')
    return jsonify(status=False, msg='课程不存在')


@work.route('/workup', methods=['post'])
@auth_required
def workup():
    """
    需要提交 k_id work_url
    作业提交接口，第一次提交直接保存，重复提交则进行修改
    """
    kid = request.form.get('k_id')
    sid = request.form.get('stu_id')
    is_k = ClzService.is_has(kid=kid)
    if kid and is_k[0]:
        s_work = dict(request.form.to_dict())
        limit = work_limit(is_k[1].get('k_time'), is_k[1].get('k_work_endtime'))
        # 判断是否可以提交 默认逾期加锁 逾期不能提交
        if isinstance(limit, int) and (limit == WorkUp.YJ or not cache.get('work_lock')):
            w_is = WorkService.is_has(sid=sid, kid=kid)
            if w_is[0]:
                version = int(w_is[1].get('version')) + 1
                work_status = int(w_is[1].get('work_status'))
                work_url = s_work.get('work_url') + "?version=" + str(version)
                if work_status == 0:
                    work_status = 2
                else:
                    work_status = work_limit(is_k[1].get('k_time'), is_k[1].get('k_work_endtime'))
                if WorkService.change(wid=w_is[1].get('id'), version=version, work_status=work_status,
                                      work_url=work_url):
                    return jsonify(status=True, msg='提交修改成功', work_url=work_url)
            else:
                s_work.setdefault('stu_id', sid)
                s_work.setdefault('work_uptime', get_time())  # 设置作业提交时间
                s_work.setdefault('work_status', limit)  # 设置作业提交状态
                s_work.setdefault('version', '0')  # 初始版本为0
                s_work['work_url'] = s_work.get('work_url') + "?version=0"
                # print s_work
                if WorkService.add(**s_work):
                    return jsonify(status=True, msg='提交成功')
        return jsonify(status=False, msg='该时段禁止提交作业')
    return jsonify(status=False, msg='课程不存在')


@work.route('/delete/<wid>', methods=['post'])
@auth_required
def delete(wid):
    if wid:
        if WorkService.remove(wid=wid):
            return jsonify(status=True, msg='删除成功')
    return jsonify(status=False, msg='删除失败')


@work.route('/do_mark/<wid>', methods=['post'])
def do_mark(wid):
    score = request.form.get('score')
    if wid > 0:
        if WorkService.do_mark(wid=wid, score=score):
            return jsonify(status=True, msg='打分成功')
    return jsonify(status=False, msg='打分失败')


@work.route('/query', methods=['post'])
@auth_required
def query():
    """
    获取作业记录
    :return:
    """
    page = int(request.form.get('page', '1'))
    year = request.form.get('year', '')
    kid = request.form.get('kid')
    sid = request.form.get('sid')
    status = request.form.get('status', '-1')
    works = WorkService.pages(page=page, year=year, k_id=kid, stu_id=sid, status=status)
    if int(works.get('total')) > 0:
        return jsonify(status=True, result=works)
    return jsonify(status=False, result={})


# 数据execl导出
@work.route('/export')
@ad_login.required
def export_1():
    year = request.args.get('year', '2018')
    kid  = int(request.args.get('kid', '0'))
    sid  = int(request.args.get('sid', '0'))
    status = request.args.get('status', '-1')
    page = WorkService.pages(1, 200000000, year=year, k_id=kid, stu_id=sid, status=status)
    filename = getWorkExecl(page.get("result"))
    return send_file(filename, as_attachment=True, attachment_filename='作业提交记录.xls')
